//
//  HWBookReadView.m
//  嗨文
//
//  Created by 响当当 on 5/15/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "HWBookReadView.h"
#import "HWMenuView.h"
#import "HWContextCell.h"
#import "HWSettingView.h"
#import "HWIndexView.h"
#import "HWNavgationView.h"
#import "HWPayBookView.h"

@interface HWBookReadView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)HWMenuView *menuView;
@property (nonatomic, strong)HWBookReaderModel *model;
@property (nonatomic, strong)HWSettingView *setingView;
@property (nonatomic, strong)HWIndexView *indexView;
@property (nonatomic, strong)HWNavgationView *navgationView;
@property (nonatomic, strong)HWPayBookView *payBookView;
@property (nonatomic, assign)NSInteger textFont;
@property (nonatomic, assign)BOOL isOpenLight;
@property (nonatomic, assign)BOOL isHideMenu;
@property (nonatomic, assign)BOOL isHideIndex;
@property (nonatomic, strong)UIColor *bgColor;
@property (nonatomic, strong)NSIndexPath *indexPath;
@end

@implementation HWBookReadView

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,IS_INCH_X ? -10*kUIScaleBasePlus : -5*kUIScaleBasePlus,SCREEN_WIDTH,SCREEN_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = 0;
        
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadUpChapter)];
        
        // 设置文字
        [header setTitle:@"上一章" forState:MJRefreshStateIdle];
        [header setTitle:@"下拉刷新" forState:MJRefreshStatePulling];
        [header setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
        
        // 设置字体
        header.stateLabel.font = [UIFont systemFontOfSize:12];
        header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:10];
        
        // 设置颜色
        header.stateLabel.textColor = LCHexColor(0x1f1f1f);
        header.lastUpdatedTimeLabel.textColor = [UIColor clearColor];
        // 设置刷新控件
        self.tableView.mj_header = header;
        
        //上拉刷新
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNextChapter)];
        //设置上拉刷新属性
        [footer setTitle:@"下一章" forState:MJRefreshStateIdle];
        [footer setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
        
        // 设置字体
        footer.stateLabel.font = [UIFont systemFontOfSize:10*kUIScaleBasePlus];
        
        // 设置颜色
        footer.stateLabel.textColor = LCHexColor(0x1f1f1f);
        
        _tableView.mj_footer = footer;
    }
    return _tableView;
}

- (HWMenuView *)menuView
{
    if (!_menuView)
    {
        _menuView = [[HWMenuView alloc]initWithFrame:CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,TABBAR_HEIGHT+20*kUIScaleBasePlus)];
        _menuView.backgroundColor = [UIColor whiteColor];
        WeakSelf(self)
        _menuView.getMenuClickBlock = ^(NSString *str) {
            [weakSelf functionClick:str];
        };
        
        _menuView.turnOrCloseLightBlock = ^(BOOL light) {
            weakSelf.isOpenLight = light;
        };
    }
    return _menuView;
}

- (HWSettingView *)setingView
{
    if (!_setingView)
    {
        _setingView = [[HWSettingView alloc]initWithFrame:CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,150*kUIScaleBasePlus)];
        _setingView.backgroundColor = [UIColor whiteColor];
        WeakSelf(self)
        _setingView.colorChangeBlock = ^(NSString *str) {
            [weakSelf changeBGColor:str];
        };
        
        _setingView.textFontChangeBlock = ^(NSInteger num) {
            weakSelf.textFont = num;
            [weakSelf.tableView reloadData];
        };
        
        _setingView.cancelSettingViewBlock = ^{
            [weakSelf removeView];
        };
        
    }
    return _setingView;
}

- (HWIndexView *)indexView
{
    if (!_indexView)
    {
        _indexView = [[HWIndexView alloc]initWithFrame:CGRectMake(0,0,-SCREEN_WIDTH,SCREEN_HEIGHT)];
        
        WeakSelf(self)
        _indexView.upLoadIndexBlock = ^(NSString *page, NSString *size) {
            [weakSelf getIndexInfo:[weakSelf.model.bookId stringValue] page:page size:size];
        };
        
        _indexView.loadChapterBlock = ^(NSString *chapterId, NSString *chapterCoin) {
            if (weakSelf.loadChapterBlock)
            {
                weakSelf.loadChapterBlock(chapterId, chapterCoin);
                [UIView animateWithDuration:0.25 animations:^{
                    weakSelf.indexView.frame = CGRectMake(0,0,-SCREEN_WIDTH,SCREEN_HEIGHT);
                    weakSelf.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
                    [weakSelf.tableView setContentOffset:CGPointMake(0,IS_INCH_X ? -50*kUIScaleBasePlus : -10*kUIScaleBasePlus) animated:NO];
                } completion:^(BOOL finished) {
                    weakSelf.isHideIndex = YES;
                    [weakSelf.indexView removeDate];
                }];
            }
        };
        
        _indexView.hideIndexBlock = ^{
            [UIView animateWithDuration:0.25 animations:^{
                weakSelf.indexView.frame = CGRectMake(0,0,-SCREEN_WIDTH,SCREEN_HEIGHT);
                weakSelf.backgroundColor = weakSelf.bgColor;
                weakSelf.alpha = 1;
            } completion:^(BOOL finished) {
                weakSelf.isHideIndex = YES;
                [weakSelf.indexView removeDate];
                [weakSelf hideMenu];
                weakSelf.isHideMenu = YES;
            }];
    
        };
    }
    return _indexView;
}

- (HWNavgationView *)navgationView
{
    if (!_navgationView)
    {
        _navgationView = [[HWNavgationView alloc]initWithFrame:CGRectMake(0,-(NAVIBAR_HEIGHT-10*kUIScaleBasePlus),SCREEN_WIDTH,NAVIBAR_HEIGHT-10*kUIScaleBasePlus)];
        _navgationView.hidden = YES;
        WeakSelf(self)
        _navgationView.getBackBlock = ^{
            if (weakSelf.getBackBlock)
            {
                weakSelf.navgationView.hidden = YES;
                weakSelf.indexView.hidden = YES;
                weakSelf.getBackBlock();
            }
        };
    }
    return _navgationView;
}

- (HWPayBookView *)payBookView
{
    if (!_payBookView)
    {
        _payBookView = [[HWPayBookView alloc]initWithFrame:CGRectMake(0,SCREEN_HEIGHT/2,SCREEN_WIDTH,SCREEN_HEIGHT/2)];
        _payBookView.backgroundColor = [UIColor whiteColor];
        WeakSelf(self)
        _payBookView.paySuccessBlock = ^{
            if (weakSelf.loadChapterBlock)
            {
                weakSelf.loadChapterBlock([weakSelf.model.chaperId stringValue], [weakSelf.model.chapterCoin stringValue]);
                [UIView animateWithDuration:0.25 animations:^{
                    weakSelf.indexView.frame = CGRectMake(0,0,-SCREEN_WIDTH,SCREEN_HEIGHT);
                    weakSelf.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
                    [weakSelf.tableView setContentOffset:CGPointMake(0,IS_INCH_X ? -50*kUIScaleBasePlus : -10*kUIScaleBasePlus) animated:NO];
                } completion:^(BOOL finished) {
                    weakSelf.isHideIndex = YES;
                    [weakSelf.indexView removeDate];
                }];
            }
        };
    }
    return _payBookView;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = LCHexColor(0xf9f9f9);
        self.textFont = contextFont;
        self.isOpenLight = NO;
        self.isHideMenu = YES;
        self.isHideIndex = YES;
        [self addSubview:self.tableView];
        [self addSubview:self.menuView];
        [self addSubview:self.setingView];
        [self addSubview:self.indexView];
        [self addSubview:self.navgationView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showMenuClick:)];
        tap.numberOfTapsRequired =1;
        tap.numberOfTouchesRequired  =1;
        [self.tableView addGestureRecognizer:tap];
    }
    return self;
}

#pragma mark - tableView delegate & datasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.model)
    {
        HWContextCell *cell = [[HWContextCell alloc]init];
        CGFloat height = [cell heightWithModel:self.model fontSize:[UIFont systemFontOfSize:self.textFont]];
        return height;
    }
    else
    {
        return SCREEN_HEIGHT;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return SCREEN_HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HWContextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bookReadCell"];
    if (!cell)
    {
        cell = [[HWContextCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"bookReadCell"];
        cell.selectionStyle = 0;
        cell.backgroundColor = [UIColor clearColor];
    }
    
    if (self.model)
    {
        [cell getContext:self.model];
        [cell changeTextFont:self.textFont context:self.model];
        self.indexPath = indexPath;
    }
    
    return cell;
}

- (void)getDate:(HWBookReaderModel *)model freeBookNum:(NSString *)num;
{
    
    self.tableView.mj_footer.hidden = NO;
    self.model = model;
    [self.tableView reloadData];
    
    if ([model.chapterOrder integerValue] > num.integerValue)
    {
        NSInteger account = [model.bookCoin integerValue]  + [model.giftCoin integerValue];
        
        if (account < [model.chapterCoin integerValue] || [[model.autoCutPay stringValue] isEqualToString:@"0"])
        {
            self.tableView.mj_footer.hidden = YES;
            self.tableView.scrollEnabled = NO;
            [self addSubview:self.payBookView];
            [self.payBookView getInfo:model];
        }
        else
        {
            if (self.payBookView)
            {
                self.tableView.scrollEnabled = YES;
                [self.payBookView removeFromSuperview];
            }
        }
    }
    
}

- (void)showPayView
{
    self.tableView.scrollEnabled = NO;
    [self addSubview:self.payBookView];
    [self.payBookView getInfo:self.model];
}

- (void)functionClick:(NSString *)str
{
    WeakSelf(self)
    switch (str.integerValue)
    {
        case 0:
        {
            [SVProgressHUD showWithStatus:@"加载中"];
            if (weakSelf.upPageContextBlock)
            {
                weakSelf.upPageContextBlock([weakSelf.model.preChapterId stringValue], [weakSelf.model.preChapterCoin stringValue]);
            }
        }
            break;
        case 1:
        {
            [weakSelf hideMenu];
            weakSelf.isHideMenu = YES;
            [self getIndexInfo:[self.model.bookId stringValue] page:@"1" size:@"30"];
        }
            break;
        case 2:
        {
            [UIView animateWithDuration:0.5 animations:^{
                   weakSelf.setingView.frame = CGRectMake(0,SCREEN_HEIGHT-150*kUIScaleBasePlus,SCREEN_WIDTH,150*kUIScaleBasePlus);
            } completion:^(BOOL finished) {
                
            }];
        }
            break;
        case 3:
        {
            if (self.isOpenLight)
            {
                [self setBackgroundColor:LCHexColor(0xf9f9f9)];
            }
            else
            {
                [self setBackgroundColor:LCHexColor(0x1d1d1f)];
            }
        }
            break;
        case 4:
        {
            [SVProgressHUD showWithStatus:@"加载中"];
            if (self.nextPageContextBlock)
            {
                self.nextPageContextBlock([self.model.nextChapterId stringValue], [self.model.nextChapterCoin stringValue]);
            }
        }
            break;
        default:
            break;
    }
    
    
}

- (void)changeBGColor:(NSString *)str
{
    
    UIColor *color = nil;
    switch (str.integerValue)
    {
        case 0:
        {
            [self setBackgroundColor:LCHexColor(0xf9f9f9)];
            color = LCHexColor(0xf9f9f9);
        }
            break;
        case 1:
        {
            [self setBackgroundColor:LCHexColor(0xf3e7d0)];
            color = LCHexColor(0xf3e7d0);
        }
            break;
        case 2:
        {
            [self setBackgroundColor:LCHexColor(0xc0dea4)];
            color = LCHexColor(0xc3dd39);
        }
            break;
        case 3:
        {
            [self setBackgroundColor:LCHexColor(0x1d1d1f)];
        }
            break;
        default:
            break;
    }
    
    
//    if (self.changeStatueBarColorBlock)
//    {
//        self.bgColor = color;
//        self.changeStatueBarColorBlock(color);
//    }
    
}

- (void)removeView
{
    WeakSelf(self)
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.setingView.frame = CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,150*kUIScaleBasePlus);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)showMenu
{
    self.navgationView.hidden = NO;
    WeakSelf(self)
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.menuView.frame = CGRectMake(0,SCREEN_HEIGHT-TABBAR_HEIGHT-20*kUIScaleBasePlus,SCREEN_WIDTH,TABBAR_HEIGHT+20*kUIScaleBasePlus);
        weakSelf.navgationView.frame = CGRectMake(0,0,SCREEN_WIDTH,NAVIBAR_HEIGHT-10*kUIScaleBasePlus);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)hideMenu
{
    WeakSelf(self)
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.menuView.frame = CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,TABBAR_HEIGHT+20*kUIScaleBasePlus);
        weakSelf.navgationView.frame = CGRectMake(0,-(NAVIBAR_HEIGHT-10*kUIScaleBasePlus),SCREEN_WIDTH,NAVIBAR_HEIGHT-10*kUIScaleBasePlus);
          weakSelf.setingView.frame = CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,150*kUIScaleBasePlus);
    } completion:^(BOOL finished) {
        self.navgationView.hidden = YES;
    }];
}

- (void)showMenuClick:(UIGestureRecognizer *)sender
{
    if (self.isHideMenu)
    {
        [self showMenu];
        self.isHideMenu = NO;
    }
    else
    {
        [self hideMenu];
        self.isHideMenu = YES;
    }
    
//    if (self.showOrHideStatueBarBlock)
//    {
//        self.showOrHideStatueBarBlock(self.isHideMenu);
//    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self hideMenu];
    self.isHideMenu = YES;
    
}

- (void)loadNextChapter
{
    [SVProgressHUD showWithStatus:@"加载中"];
    WeakSelf(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (weakSelf.nextPageContextBlock)
        {
            weakSelf.nextPageContextBlock([weakSelf.model.nextChapterId stringValue], [weakSelf.model.nextChapterCoin stringValue]);
            [weakSelf.tableView setContentOffset:CGPointMake(0,IS_INCH_X ? -50*kUIScaleBasePlus : -10*kUIScaleBasePlus) animated:NO];
        }
        [weakSelf.tableView.mj_footer endRefreshing];
        
    });
}

- (void)loadUpChapter
{
    [SVProgressHUD showWithStatus:@"加载中"];
    WeakSelf(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (weakSelf.upPageContextBlock)
        {
            weakSelf.upPageContextBlock([weakSelf.model.preChapterId stringValue], [weakSelf.model.preChapterCoin stringValue]);
        }
        
        [weakSelf.tableView.mj_header endRefreshing];
        
    });
}

#pragma mark - 加载目录
- (void)getIndexInfo:(NSString *)bookId page:(NSString *)page size:(NSString *)size
{
    NSDictionary *prarmers = @{
                               @"access_token" : current_User.token,
                               @"bookId" : bookId,
                               @"pageNum" : page,
                               @"pageSize" : size
                               };
    
    WeakSelf(self)
    [MyInfoManager getBookIndexInfo:prarmers sucess:^(id  _Nonnull acceptData)
     {
         NSNumber *nub = IFNULL(acceptData[@"hasNextPage"], [NSNumber new]);
         
         [weakSelf.indexView getDate:acceptData[@"list"] hasNetPage:nub];

         if (weakSelf.isHideIndex)
         {
             [UIView animateWithDuration:0.25 animations:^{
                 weakSelf.indexView.frame = CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
                 weakSelf.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.75];
             } completion:^(BOOL finished) {
                 weakSelf.isHideIndex = NO;
             }];
         }
         
     } fail:^(NSError * _Nullable error) {
         DISMISS_SVP(1.0f);
         [SVProgressHUD showErrorWithStatus:@"获取失败，请检查网络是否良好"];
         DISMISS_SVP(1.0f);
     }];
}



@end
